package com.lanwf.admin.utils;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

/**
 * 采用3DES加密，单des密钥是8字节，三重des密钥就是3*8=24字节,更加安全
 * 即密钥必须是24位
 */
public class TripleDes {

    private TripleDes(){}

    private static  Cipher DES_CIPHER;
    static {
        try {
            DES_CIPHER = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密
     * @param str 明文字符串
     * @param key 密钥（必须24位）
     * @return
     */
    public static String encrypt3DES(String str, String key) {
        if(StringUtils.isBlank(str))return null;
        try {
            DES_CIPHER.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "DESede"));
            byte[] encryptedData = DES_CIPHER.doFinal(str.getBytes("utf-8"));
            //转化为字符串
            return Hex.encodeHexString(encryptedData).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param str 密码后的密文
     * @param key 密钥（必须24位）
     * @return
     */
    public static String decrypt3DES(String str, String key) {
        if(StringUtils.isBlank(str))return null;

        try {
            DES_CIPHER.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "DESede"));
            byte[] decryptedData = DES_CIPHER.doFinal(Hex.decodeHex(str.toCharArray()));
            return new String(decryptedData, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static void main(String[] args) throws UnsupportedEncodingException {

        byte[] bytes = "风险管理".getBytes();
        System.err.println(bytes);

        byte[] bytes1 = "风险管理".getBytes();
        System.err.println(bytes1);

        byte[] bytes2 = "自动化办公".getBytes();
    }

}